<?php

namespace app\api\controller;

use think\Controller;
use think\Request;

class Article extends controller
{
    public function getArticleList(Request $request)
    {
        $search = $request->get('search', '', 'trim');
        $category_id = $request->get('category_id', 0, 'intval');
        $page = $request->get('page', 1, 'intval');
        $page = $page > 0 ? $page : 1;
        $article = Db('article')->alias('a')->join('category c', 'a.category_id = c.category_id', 'LEFT')->join('teacher t', 'a.teacher_id = t.teacher_id', 'LEFT');
        if ($category_id) {
            $article->where('a.category_id', $category_id);
        }
        if ($search) {
            $article->where('a.title|a.description', 'like', '%' . $search . '%');
            if (Db('search')->where('word', $search)->find()) {
                Db('search')->where('word', $search)->setInc('num');
            } else {
                Db('search')->insert(['word' => $search, 'num' => 1]);
            }
        }
        $list = $article
            ->field('a.article_id,a.category_id,a.title,a.image,a.start_time,a.description,t.name as teacher_name,t.avatar as teacher_avatar,t.age as teacher_age,c.name as category_name')
            ->order('a.sort asc')
            ->page($page, 10)
            ->select();
        return ['code' => 0, 'data' => $list];
    }

    public function getArticleInfo(Request $request)
    {
        $article_id = $request->get('article_id', 0, 'intval');
        $info = Db('article')
            ->alias('a')
            ->join('teacher t', 'a.teacher_id = t.teacher_id', 'LEFT')
            ->join('category c', 'a.category_id = c.category_id', 'LEFT')
            ->field('a.*,t.name as teacher_name,t.avatar as teacher_avatar,t.age as teacher_age,c.name as category_name')
            ->where('a.article_id', $article_id)
            ->find();
        if (!$info) {
            return ['code' => 2, 'msg' => '课程已下架'];
        }
        return ['code' => 0, 'data' => $info];
    }
}
